<template>
  <view class="consumer_box">
    <navBar :navbarData.sync="navbarData"></navBar>
    <view class="consumer_view">
      <img class="survey_top_img"
        src="https://100000063-1252208446.file.myqcloud.com/images/macallan-remvp/survey/survey_top_img.jpg" />
      <view class="consumer_content" v-if="thisSurveyObj">
        <view class="consumer_title">{{ surveyQuestionTitle }} </view>

        <!-- 通过id 获取问题数据对象-->
        <view class="consumer_description">
          {{ thisSurveyObj.question }} <text class="survey_type">{{ thisSurveyObj.type == 1 ? '（单选）' :
      thisSurveyObj.type == 2 ?
        '（多选）' : thisSurveyObj.type == 3 ? '（填空）' : '' }}</text>
        </view>
        <radioCom ref="radioRef" v-if="thisSurveyObj.type == 1 && thisSurveyObj.options"
          :optionList="thisSurveyObj.options" @radioChange="radioChange" />
        <checkCom ref="checkRef" @checkChangeIndex="checkChangeIndex"
          v-else-if="thisSurveyObj.type == 2 && thisSurveyObj.options" :optionList="thisSurveyObj.options" />
        <view v-else-if="thisSurveyObj.type == 3 && thisSurveyObj.options" class="consumer_input_box">
          <input v-model="inputValue" @input="changeInput" type="text" placeholder-style="color:#C6C6C6" class="consumer_input"
            maxlength="40" placeholder="请输入" style="font-size: 32rpx; line-height: 48rpx"
            :style="{ color: inputValue ? '#757575' : '#C6C6C6' }" />
        </view>
      </view>
    </view>
    <view class="def_btn" :class="consumerButtom">
      <view style="margin-right: 16rpx" :class="btnPreviousClass" v-if="surveyQuestionIndex !== 0 ||this.userSurveyQuestionList "
        @click.stop="changePrevious">
        上一题</view>
      <view :class="btnNextClass" @click.stop="changeNext" v-if="!isLastSurveyQuestion">下一题</view>

      <view v-else :class="btnNextClass" @click.stop="changeSubmit">提交</view>

    </view>
    <!-- ios 底部安全区 -->
    <view class="ios_safe_zone" v-if="isIos">
      <view class="ios_safe_zone_line"></view>
    </view>
    <!-- 弱提示 弹窗 -->
    <toast-popup ref="toastPopup" @onToastPopupClick="onToastPopupClick"></toast-popup>
  </view>
</template>

<script>
import api from "@/api/api";
import { CUSTOMER_INFO } from "@/utils/constant";
import NavBar from "../../components/common/navbar";
import radioCom from "./components/radioCom.vue";
import checkCom from "./components/checkCom.vue";

export default {
  components: {
    navBar: NavBar,
    radioCom,
    checkCom,
  },
  data() {
    return {
      navbarData: {
        showCapsule: 0, //是否显示左上角图标   1表示显示    0表示不显示
        title: "",
        navbarTitle: "",
        isTopFixed: true,
        isIos: false,
      },
      isFinishSurvey: false, //	用户是否已完成问卷调查
      surveyQuestionStatus: null, //	当前问卷的状态 1为正常 0为已结束
      surveyQuestionList: [], //	问卷问题列表
      surveyQuestionCode: null, //	问卷编码
      surveyQuestionDesc: "", //  问卷调查描述
      surveyQuestionTitle: "", //  问卷调查标题
      // surveyQuestionIndex: 0, //  问卷调查索引
      surveyQuestionIndex: 0, //	当前问卷问题索引
      radioSubData: null, // 单选按钮选中值
      checkSubList: [], // 多选按钮选中值
      thisSurveyObj: null, //	当前问卷问题对象
      inputValue: "",
      isValState: false, //是否填写有值
      shareImage: "",
      shareTitle: "",
      pagePath: "",
      pageQuery: "",
      userSurveyQuestionList: [], //	用户问卷问题列表
      isLastSurveyQuestion: false, //	是否最后一题
    };
  },
  computed: {
    consumerButtom() {
      return this.surveyQuestionIndex !== 0 ? "consumer_buttom" : "";
    },
    btnPreviousClass() {
      if (this.surveyQuestionIndex === 0) {
        return "btn_previous_def";
      } else {
        return "btn_previous_small";
      }
    },
    btnNextClass() {
      console.log(this.surveyQuestionIndex, 'this.surveyQuestionIndex')
      if (this.surveyQuestionIndex === 0) {
        return this.isValState ? 'btn_next' : 'btn_previous_def'
      } else {
        // 判断是否选中值
        return this.isValState ? "btn_next_small" : "btn_next_small_def";
      }
    },
  },
  async onLoad(option) {
    this.isIos =
      wx.getSystemInfoSync().system.includes("iOS") &&
      wx.getSystemInfoSync()?.safeArea?.top > 20;
    //  用户未登录 调用登录接口
    const customerInfo = uni.getStorageSync(CUSTOMER_INFO);
    if (!customerInfo || !customerInfo.openId) {
      await this.$commonFunction.commonLoginNew();
    }
    await this.initPage(option);
  },
  onShow() { },
  onUnload() { },
  onHide() { },
  methods: {
    changeSubmit() {

    },
    checkChangeIndex(checkList) {
      this.checkSubList = checkList
      console.log(checkList, 'checkListcheckList')
      this.isValState = !!checkList.length

    },
    radioChange(itemObj) {
      if (itemObj) {
        this.radioSubData = itemObj
        this.isValState = true
        console.log(itemObj, 'itemObj')
      } else {
        this.radioSubData = null
        this.isValState = false
      }
    },
    // 下一题
    changeNext() {
      if(!this.isValState)return
      const { surveyCode, id } = this.thisSurveyObj
      console.log(this.thisSurveyObj, 'surveyQuestionIndex')

      const answer = this.thisSurveyObj.type === 1 ? this.radioSubData : this.thisSurveyObj.type === 2 ? this.checkSubList : this.inputValue
      const data = {
        surveyCode,
        questionId: id,
        answer: JSON.stringify(answer),
      }
      // 有没有结束  
      if (this.radioSubData.skipquestion && this.radioSubData.nextquestion === -1 || this.surveyQuestionList.length === this.surveyQuestionIndex + 1) {
        data.isFinish = true
        this.isLastSurveyQuestion = true
        return
      }
      console.log(data, 'datadatadatadata')
      // 当前选项是否有跳转下一题
      if (this.radioSubData.skipquestion) {
        this.thisSurveyObj = this.surveyQuestionList.find(i => i.id == this.radioSubData.nextquestion)
        this.surveyQuestionIndex = this.surveyQuestionList.findIndex(i => i.id == this.thisSurveyObj.id)
        console.log(this.surveyQuestionIndex, 'this.surveyQuestionIndex1')
      } else {
        // 没有则走索引 拿到当前的索引 加1 拿到下一题
        this.surveyQuestionIndex = this.surveyQuestionIndex + 1
        this.thisSurveyObj = this.surveyQuestionList[this.surveyQuestionIndex]
        console.log(this.surveyQuestionIndex, 'this.surveyQuestionIndex2')
      }
      console.log(this.thisSurveyObj, 'this.thisSurveyObj', this.surveyQuestionList.length, this.surveyQuestionIndex)


      this.userSurveyQuestionList.push(this.thisSurveyObj)
      // 去重
      this.userSurveyQuestionList = [...new Map(this.userSurveyQuestionList.map(item => [item.id, item])).values()];
      console.log(this.userSurveyQuestionList, 'this.userSurveyQuestionList')
      this.isValState = false
      this.clearCheck()
    },
    clearCheck() {
      if (this.thisSurveyObj.type === 1) {
        this.$refs.radioRef?.clear()
      } else if (this.thisSurveyObj.type === 2) {
        this.$refs.checkRef?.clear()
      } else {
        this.inputValue = ''
      }
    },
    // 上一题
    changePrevious() {
      // 没有关联id 根据id去重
      console.log(this.userSurveyQuestionList, 'this.userSurveyQuestionList')
      this.userSurveyQuestionList = [...this.userSurveyQuestionList] // 创建新数组引用
      this.userSurveyQuestionList.pop();
      
      this.thisSurveyObj = this.userSurveyQuestionList[this.userSurveyQuestionList.length - 1]
      this.$forceUpdate(); // 强制更新视图
      this.clearCheck()
    },
    changeInput(e) {
      this.isValState = this.inputValue.length > 0;
    },
    /**
     * 初始化问卷数据
     * @param {Object} option
     */
    async initPage(option) {
      try {
        let customerData = uni.getStorageSync(CUSTOMER_INFO);
        //	再次判断用户是否已经登录，并查询openid
        if (!customerData || !customerData.openId) {
          await this.$commonFunction.commonLoginNew();
          customerData = uni.getStorageSync(CUSTOMER_INFO);
        }
        if (option && option.code) {
          const surveyRes = await api.getSurveyListsByCode({
            code: option.code,
            open_id: customerData.openId,
          });
          console.log("#### surveyRes", surveyRes);
          if (surveyRes.success && surveyRes.data) {
            this.isFinishSurvey = surveyRes.data.finish;
            const _surveyObj = surveyRes.data.survey || null;
            if (_surveyObj && _surveyObj.id) {
              this.surveyQuestionStatus = _surveyObj.status;
              this.surveyDataAssembly(_surveyObj.surveyQuestionList);
              this.surveyQuestionCode = _surveyObj.code;
              this.surveyQuestionDesc = _surveyObj.description;
              this.surveyQuestionTitle = _surveyObj.title;
            }
            if (_surveyObj.status != 1) {
              this.handleShowTextToast("您访问的问卷调研已到期结束");
            }
            return;
          }
        }
        this.handleShowTextToast("问卷数据获取失败！");
      } catch (e) {
        console.log("######  initPage---error:", e);
        this.handleShowTextToast("问卷数据异常，请稍后再试！");
      }
    },

    /**
     * 调查问卷 问题类型数据处理
     * @param {Object} questionList
     */
    async surveyDataAssembly(questionList) {
      try {
        this.surveyQuestionList = [];
        for (let i = 0; i < questionList.length; i++) {
          const el = questionList[i];
          if (!!el.options) {
            el.options = JSON.parse(el.options);
          }
          this.surveyQuestionList.push(el);
        }
        console.log("this.surveyQuestionList", this.surveyQuestionList);
        this.thisSurveyObj = this.surveyQuestionList[0];
        this.userSurveyQuestionList.push(this.thisSurveyObj)
        console.log(this.thisSurveyObj, "this.thisSurveyObj");
      } catch (e) {
        console.log("e", e);
      }
    },
    /**
     * 展示弱提示
     * @param {Object} msg 文案
     */
    handleShowTextToast(msg) {
      try {
        this.$refs.toastPopup.showToast(msg);
      } catch (e) { }
    },
    /**
     * 若提示按钮点击回调
     * @param {Object} data.type 类型：confirm确定，cancel取消
     * @param {Object} data.callBackData 呼气弹窗时传入的数据
     */
    onToastPopupClick(data) { },
    onShareAppMessage(res) {
      let that = this;
      if (res.from === "button") {
      } else {
        this.$EFSTracking.trackingAction("SHARE_CARD", res.from, {});
      }
      let imageUrl = this.shareImage;
      let path = this.pageQuery
        ? `/${this.pagePath}?${this.pageQuery}`
        : `/${this.pagePath}`;
      let title = this.shareTitle;
      this.$commonSensors.sensorsPageShare();
      this.$sr.setContext({
        share_title: title || "THE MACALLAN EBOUTIQUE麦卡伦",
      });
      return this.$commonFunction.commonShare(
        res,
        this.shareTitle,
        path,
        this.shareImage
      );
    },
    onShareTimeline() {
      const title = this.shareTitle
        ? this.shareTitle
        : uni.getStorageSync("storeName") || "THE MACALLAN EBOUTIQUE麦卡伦";
      this.$sr.setContext({
        share_title: title || "THE MACALLAN EBOUTIQUE麦卡伦",
      });
      return {
        title: title,
        query: this.pageQuery,
        imageUrl: this.shareImage,
      };
    },
  },
};
</script>

<style lang="less">
.consumer_box {
  position: relative;

  .consumer_view {
    height: 100vh;
    display: flex;
    flex-direction: column;
  }

  .consumer_content {
    flex: 1;
    padding: 64rpx 48rpx 0 48rpx;

    .consumer_title {
      font-size: 36rpx;
      line-height: 52rpx;
      margin-bottom: 48rpx;
    }

    .consumer_description {
      font-size: 28rpx;
      line-height: 48rpx;
      color: #000000;
      margin-bottom: 32rpx;

      .survey_type {
        font-size: 28rpx;
        line-height: 48rpx;
        color: #757575;
      }
    }

    .consumer_input_box {
      width: 100%;
      height: 142rpx;

      .consumer_input {
        width: 100%;
        height: 100%;
      }
    }
  }
}

.survey_top_img {
  width: 750rpx;
  height: 616rpx;
}

.def_btn {
  width: 100%;
  position: absolute;
  bottom: 132rpx;
  padding: 0 48rpx;
}

.consumer_buttom {
  width: 100%;
  display: flex;
  //   justify-content: space-between;
}

.btn_previous_def {
  height: 80rpx;
  width: 654rpx;
  display: flex;
  justify-content: center;
  align-items: center;
  background-color: #c6c6c6;
  color: #757575;
  border-radius: 50.5rpx 16.8rpx 50.5rpx 50.5rpx;
}

.btn_next {
  height: 80rpx;
  width: 654rpx;
  display: flex;
  justify-content: center;
  align-items: center;
  background: #000000;
  color: #ffffff;
  border-radius: 50.5rpx 16.8rpx 50.5rpx 50.5rpx;
}

.btn_previous_small {
  width: 319rpx;
  height: 80rpx;
  display: flex;
  justify-content: center;
  align-items: center;
  border-radius: 48rpx 16rpx 48rpx 48rpx;
  border: 4rpx solid #000000;
  color: #000000;
}

.btn_next_small {
  width: 319rpx;
  height: 80rpx;
  display: flex;
  justify-content: center;
  align-items: center;
  border-radius: 48rpx 16rpx 48rpx 48rpx;
  background: #000000;
  color: #ffffff;
}

.btn_next_small_def {
  width: 319rpx;
  height: 80rpx;
  display: flex;
  justify-content: center;
  align-items: center;
  border-radius: 48rpx 16rpx 48rpx 48rpx;
  background: #c6c6c6;
  color: #757575;
}
</style>
